package com.dzh.controller;

import com.dzh.entities.CommonResult;
import com.dzh.entities.Payment;
import com.dzh.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author DZH
 * @createTime 2021/7/18 19:57
 */
@RestController
@Slf4j
@EnableEurekaClient
@EnableDiscoveryClient
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping(value = "/payment/insert")
    public CommonResult insert(@RequestBody Payment payment){
        int result=paymentService.insert(payment);
        log.info("**********插入结果:"+result);

        if (result>0){
            return new CommonResult(200,"插入数据库成功,端口号: "+serverPort,result);
        }else {
            return new CommonResult(-200,"插入数据库失败");
        }

    }

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("**********插入结果:"+paymentById);

        if (paymentById!=null){
            return new CommonResult(200,"查询成功,端口号: "+serverPort,paymentById);
        }else {
            return new CommonResult(-200,"没有对应数据,查询Id:"+id);
        }

    }
    @GetMapping(value = "/payment/discovery")
    public Object discovery(){
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            System.out.println("************service: "+service);
        }
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance instance : instances) {
            log.info(instance.getInstanceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }
        return  discoveryClient;

    }
}
